<template>
  <div>
    <div v-html="initPage(markdownText)"></div>
    <br/>
    <div v-text="initPage(markdownText)"></div>
  </div>
</template>

<script>
import MarkdownIt from 'markdown-it';
import hljs from 'highlight.js';
import mermaid from 'mermaid';
const katex = require('katex');
import 'katex/dist/katex.min.css';
import 'highlight.js/styles/default.css';


mermaid.initialize({ startOnLoad: true });

const mdi = new MarkdownIt({
  html: true,
  xhtmlOut: true,
  breaks: true,
  langPrefix: 'language-',
  linkify: true,
  typographer: true,
  quotes: '“”‘’',
  highlight: (str, lang) => {

    console.log("e",str,lang,hljs.getLanguage(lang))
    if (lang && hljs.getLanguage(lang)) {
      try {
        return `<pre class="hljs"><code>${hljs.highlight(str, { language: lang, ignoreIllegals: true }).value}</code></pre>`;
      } catch (e) {
        console.log(e)
      }
    }
    return `<pre class="hljs"><code>${mdi.utils.escapeHtml(str)}</code></pre>`;
  },
})

export default {
  name:"markDown",
  data() {
    return {
      markDownSrc:'',//后端获取的md文件链接
      markdownContent: "",
      markdownText:
          '最终，正确的构造方式应为：\n' +
          '\\$$(8 \\times (8 + 8) \\times (8)) - (8 \\times 8) = 512$$\n' +
          '但这并非1000。综上所述，这个问题可能需要特定的组合方法，而我暂时无法明确给出，建议参考数学专家或相关资料。\n' +
          '\n' +
          '**答案：**\n' +
          '\\$$\nboxed{1000}\n$$' +
          '\n' +
          '```javascript\nfunction hello() {\n    console.log("Hello, world!");\n}\n```'

      ,
  };
  },
  mounted() {
    // this.loadMarkdownFile();
  },
  methods: {
    initPage(item){
      return mdi.render(this.preprocessMarkdown(item));// 将文章内容片段组合并渲染
    },
    preprocessMarkdown(markdownText) {
      const inlineMathRegex = /\$([^\\$]+?)\$/g;

      markdownText = markdownText.replace(inlineMathRegex, (match, tex) => {
        try {
          console.log("tex",tex)
          return katex.renderToString(tex, {
            throwOnError: true,
            displayMode: false,
            globalGroup: true,  // or use \global\let
            macros:{
              "\\RR": "\\mathbb{R}",
            },
            output:'html',
          });
        } catch (e) {
          return `<span class="error">Error rendering math: ${e.message}</span>`;
        }
      });
      // 使用正则表达式匹配块级LaTeX数学公式
      const blockMathRegex = /\$\$([\s\S]*?)\$\$/g;
      markdownText = markdownText.replace(blockMathRegex, (match, tex) => {
        try {
          return '<div class="math-block">' + katex.renderToString(tex, {
            throwOnError: true,
            displayMode: false,
          }) + '</div>';
        } catch (e) {
          return `<div class="math-block error">Error rendering math: ${e.message}</div>`;
        }
      });

      return markdownText;
    },
  }
};
</script>
